package com.qxzn.app.medicalhealth.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.api.util.EventBusManager;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.ContactsBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.bean.MedicineCaseDetailBean;
import com.qxzn.app.bean.MedicineRecordImgBean;
import com.qxzn.app.medicalhealth.R;
import com.qxzn.app.medicalhealth.R2;
import com.qxzn.app.medicalhealth.adapter.AddMedicalCaseImgAdapter;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.util.GlideImageLoader;
import com.qxzn.app.page.view.CustomItemView;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.FileUtil;
import com.qxzn.app.util.MathUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import news.jaywei.com.compresslib.CompressTools;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 添加病历、病历详情
 */
public class AddMedicalRecordActivity extends BaseActivity {

    @BindView(R2.id.rl_root)
    RelativeLayout rlRoot;
    @BindView(R2.id.tv_disclaimer)
    TextView tvDisclaimer;
    @BindView(R2.id.tv_save)
    TextView tvSave;
    @BindView(R2.id.lrv_img)
    LRecyclerView lrvImg;
    private String title;
    public static final String addMedicalRecord = "添加病历";
    public static final String medicalRecordDetails = "病历详情";
    private ContactsBean.DataBean userBean;
    private String username;
    private RxPermissions rxPermissions;
    private List<MedicineRecordImgBean> imgList = new ArrayList<>();
    private int maxImgSelectable = 11;
    private LRecyclerViewAdapter recyclerViewAdapter;
    private AddMedicalCaseImgAdapter adapter;
    private ViewHolder headViewHolder;
    private String id;
    private String delIds = "";

    @Override
    protected int initLayout() {
        return R.layout.activity_add_medical_record;
    }

    @Override
    protected void initView() {
        lrvImg.setLayoutManager(new GridLayoutManager(this, 3));
        adapter = new AddMedicalCaseImgAdapter(this, imgList);
        adapter.setDelClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag();
                MedicineRecordImgBean bean = imgList.get(position);
                if (!TextUtils.isEmpty(bean.getId()) && TextUtils.isEmpty(delIds)) {
                    delIds += bean.getId();
                } else {
                    delIds += "," + bean.getId();
                }
                imgList.remove(position);
                adapter.notifyDataSetChanged();
            }
        });
        recyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        lrvImg.setAdapter(recyclerViewAdapter);
        recyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                AppUtil.showLog("点击位置：" + position);
                if (position == 0) {
                    if (imgList.size() < maxImgSelectable) {
                        getPermission(1);
                    } else {
                        AppUtil.showToast(AddMedicalRecordActivity.this, "最多只能选择" + (maxImgSelectable - 1) + "张病例照片");
                    }
                }
            }
        });
        lrvImg.setPullRefreshEnabled(false);
        lrvImg.setLoadMoreEnabled(false);
        View headView = LayoutInflater.from(this).inflate(R.layout.head_add_medical_record, (ViewGroup) findViewById(android.R.id.content), false);
        headViewHolder = new ViewHolder(headView);
        recyclerViewAdapter.addHeaderView(headView);
//        View footView = LayoutInflater.from(this).inflate(R.layout.item_remind_detail_foot, (ViewGroup)findViewById(android.R.id.content), false);
//        recyclerViewAdapter.addFooterView(footView);
//        rlRoot.getViewTreeObserver().addOnGlobalLayoutListener(() -> setStatusBar());
    }

    @Override
    protected void iniTitleBar() {
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        userBean = (ContactsBean.DataBean) getIntent().getSerializableExtra("user_data");
        if (userBean != null) {
            username = userBean.getMemName();
            String remark = userBean.getMemRemarks();
            if (!TextUtils.isEmpty(remark)) {
                remark = "(" + remark + ")";
            } else {
                remark = "";
            }
            headViewHolder.tvName.setText(userBean.getMemName() + remark);
            headViewHolder.tvAge.setText("年龄：" + userBean.getAge() + "岁");
            Glide.with(this).load(userBean.getHeadportrait()).apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.mipmap.logo).error(R.mipmap.logo)).into(headViewHolder.ivHead);
        } else {
            id = getIntent().getStringExtra("id");
            if (!TextUtils.isEmpty(id)) {
                getCasesDetail();
            } else {
                AppUtil.showToast(AddMedicalRecordActivity.this, "参数有误");
                finish();
                return;
            }
        }
        title = getIntent().getStringExtra("title");
        tv_title.setText(title);
        if (medicalRecordDetails.equals(title)) {
            tvSave.setText("修改");
            TextView textView = new TextView(this);
            textView.setId(R.id.tv_delete);
            textView.setText("删除");
            textView.setTextColor(getResources().getColor(R.color.white));
            textView.setOnClickListener(this);
            ll_right_bar.addView(textView);
        } else {
            tvSave.setText("保存");
        }
        imgList.add(null);
        adapter.notifyDataSetChanged();
        recyclerViewAdapter.notifyDataSetChanged();
    }

    @OnClick({R2.id.tv_save})
    public void onViewClicked(View view) {
        int id = view.getId();
        AppUtil.showLog("--" + id);
        if (id == R.id.tv_save) {
            if (TextUtils.isEmpty(headViewHolder.civMedicalRecordName.getRightEditText())) {
                AppUtil.showToast(this, headViewHolder.civMedicalRecordName.getRightEditHintText());
                return;
            }
            if (TextUtils.isEmpty(headViewHolder.etDescribe.getText().toString().trim())) {
                AppUtil.showToast(this, headViewHolder.etDescribe.getHint().toString().trim());
                return;
            }
            if (imgList.size() < 2) {
                AppUtil.showToast(this, "请选择对应的病例照片");
                return;
            }
            addCases();
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.tv_delete) {
            showDialog("删除操作", "是否确认删除？删除之后数据将不可还原", (dialog, which) -> delCasesRecord());
        }
    }

    private void getPermission(int requestCode) {
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this);
        }
        rxPermissions.requestEachCombined(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(permission -> {
                    if (permission.granted) {
                        getPicture(maxImgSelectable - imgList.size(), requestCode);
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        showPermissionDialog("该功能需要存储权限和相机权限", (dialog, which) -> {
                            getPermission(requestCode);
                        });
                    } else {
                        showPermissionDialog("该功能需要存储权限和相机权限");
                    }
                });
    }

    private void getPicture(int maxSelectable, int requestCode) {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .capture(true)
                .maxSelectable(maxSelectable)
                .captureStrategy(new CaptureStrategy(true, Constant.authority))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideImageLoader.Glide4Engine())
                .forResult(requestCode);
    }

    private void compressImg(int requestCode, String faceIdPath) {
        File file = new File(faceIdPath);
        AppUtil.showLog(file.exists() + "：路径：" + file);
        CompressTools tool = new CompressTools.Builder(this).setDestinationDirectoryPath(FileUtil.getBaseImagePath(this)).build();
        tool.compressToFileJni(file, new CompressTools.OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                AppUtil.showLog(file.exists() + "压缩成功：" + file);
                imgList.add(new MedicineRecordImgBean(file));
                adapter.notifyDataSetChanged();
                recyclerViewAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<String> mSelected = Matisse.obtainPathResult(data);
            AppUtil.showLog("mSelected: " + mSelected + "\n");
            if (mSelected != null && mSelected.size() > 0) {
                for (int i = 0; i < mSelected.size(); i++) {
                    compressImg(requestCode, mSelected.get(i));
                }
            }
        }
    }

    private void addCases() {
        showProgress();
        List<MultipartBody.Part> files = new ArrayList<>();
        for (int i = 1; i < imgList.size(); i++) {
            MedicineRecordImgBean bean = imgList.get(i);
            Object img = bean.getObject();
            if (img != null && img instanceof File) {
                File file = new File(img + "");
                if (file != null && file.exists()) {
                    files.add(HttpRequest.getPartFileBody(file, MathUtil.getRandom(6, MathUtil.LETTER_CHAR)));
                }
            }
        }
        Call<BaseBean> call;
        if (medicalRecordDetails.equals(title)) {//修改
            call = HttpRequest.getService().updateCasesRecord(HttpRequest.getPartBody(delIds), HttpRequest.getPartBody(id),
                    HttpRequest.getPartBody(headViewHolder.civMedicalRecordName.getRightEditText()), HttpRequest.getPartBody(headViewHolder.etDescribe.getText().toString().trim()), files);
        } else {//新增
            call = HttpRequest.getService().addCasesRecord(HttpRequest.getPartBody(username), HttpRequest.getPartBody(SharePreferenceUtil.getDeviceId(this)),
                    HttpRequest.getPartBody(headViewHolder.civMedicalRecordName.getRightEditText()), HttpRequest.getPartBody(headViewHolder.etDescribe.getText().toString().trim()), files);
        }
        call.enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                hideProgress();
                BaseBean baseBean = response.body();
                if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
                    AppUtil.showToast(AddMedicalRecordActivity.this, baseBean.getMsg());
                } else {
                    if (medicalRecordDetails.equals(title)) {//修改
                        AppUtil.showToast(AddMedicalRecordActivity.this, "修改成功");
                    } else {
                        AppUtil.showToast(AddMedicalRecordActivity.this, "添加成功");
                    }
                }
                if (baseBean != null && baseBean.getCode() == 200) {
                    EventBusManager.post(new EventBusBean.Builder().id(4).build());
                    setResult(RESULT_OK);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                hideProgress();
                AppUtil.showToast(AddMedicalRecordActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

    private void getCasesDetail() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        Call<MedicineCaseDetailBean> call = HttpRequest.getService().getMedicineCaseDetail(body);
        call.enqueue(new Callback<MedicineCaseDetailBean>() {
            @Override
            public void onResponse(Call<MedicineCaseDetailBean> call, Response<MedicineCaseDetailBean> response) {
                MedicineCaseDetailBean baseBean = response.body();
                if (baseBean != null && baseBean.getCode() == 200 && baseBean.getData() != null) {
                    MedicineCaseDetailBean.DataBean dataBean = baseBean.getData();
                    String remark = dataBean.getNiname();
                    if (!TextUtils.isEmpty(remark)) {
                        remark = "(" + remark + ")";
                    } else {
                        remark = "";
                    }
                    username = dataBean.getUsername();
                    headViewHolder.tvName.setText(username + remark);
                    headViewHolder.tvAge.setText("年龄：" + dataBean.getAge() + "岁");
                    Glide.with(AddMedicalRecordActivity.this).load(HttpRequest.BASE_URL + dataBean.getHeadportrait()).apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.mipmap.logo).error(R.mipmap.logo)).into(headViewHolder.ivHead);
                    headViewHolder.civMedicalRecordName.setRightEditText(dataBean.getCasename());
                    headViewHolder.etDescribe.setText(dataBean.getContent());
                    List<MedicineCaseDetailBean.DataBean.PicturesBean> imgs = dataBean.getPictures();
                    if (imgs != null) {
                        for (MedicineCaseDetailBean.DataBean.PicturesBean img : imgs) {
                            imgList.add(new MedicineRecordImgBean(img.getId(), HttpRequest.BASE_URL + img.getUrl()));
                        }
                        adapter.notifyDataSetChanged();
                    }
                    return;
                }
                if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
                    AppUtil.showToast(AddMedicalRecordActivity.this, baseBean.getMsg());
                } else {
                    AppUtil.showToast(AddMedicalRecordActivity.this, "修改成功");
                }
            }

            @Override
            public void onFailure(Call<MedicineCaseDetailBean> call, Throwable t) {
                hideProgress();
            }
        });
    }

    private void delCasesRecord() {
        if (TextUtils.isEmpty(id)) {
            AppUtil.showToast(this, "数据有误");
            return;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        Call<BaseBean> call = HttpRequest.getService().delCasesRecord(body);
        call.enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                BaseBean bean = response.body();
                if (bean != null) {
                    if (bean.getCode() == 200) {
                        if (!TextUtils.isEmpty(bean.getMsg())) {
                            AppUtil.showToast(AddMedicalRecordActivity.this, bean.getMsg());
                        } else {
                            AppUtil.showToast(AddMedicalRecordActivity.this, "删除成功");
                        }
                        EventBusManager.post(new EventBusBean.Builder().id(4).build());
                        finish();
                        return;
                    }
                }
                if (bean != null && !TextUtils.isEmpty(bean.getMsg())) {
                    AppUtil.showToast(AddMedicalRecordActivity.this, bean.getMsg());
                } else {
                    AppUtil.showToast(AddMedicalRecordActivity.this, "网络错误，请稍后再试！");
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                AppUtil.showToast(AddMedicalRecordActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

    static class ViewHolder {
        @BindView(R2.id.tv_name)
        TextView tvName;
        @BindView(R2.id.tv_age)
        TextView tvAge;
        @BindView(R2.id.iv_head)
        ImageView ivHead;
        @BindView(R2.id.civ_medical_record_name)
        CustomItemView civMedicalRecordName;
        @BindView(R2.id.et_describe)
        EditText etDescribe;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
